package com.yehuo.app.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuo.app.dto.APPOrderDto;
import com.yehuo.app.dto.CreateOrderDTO;
import com.yehuo.app.dto.OrderDTO;
import com.yehuo.app.entity.*;
import com.yehuo.app.mapper.*;
import com.yehuo.app.model.APP;
import com.yehuo.app.schedule.DelayQueueManager;
import com.yehuo.app.schedule.DelayTask;
import com.yehuo.app.service.AppOrderService;
import com.yehuo.app.service.UserPasswordService;
import com.yehuo.app.util.wx.WXPay;
import com.yehuo.app.util.wx.WXPayConfigImpl;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import com.yehuo.app.util.wx.constants.WXPayConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class AppOrderServiceImpl implements AppOrderService {
    public static final DateTimeFormatter MILLISECOND = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
    @Autowired
    private AppOrderMapper orderMapper;
    @Autowired
    private UserPasswordService userPasswordService;
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserWXMapper userWXMapper;
    @Autowired
    private WthdrawalMapper wthdrawalMapper;
    @Autowired
    private DictMapper dictMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderRedPacketMapper redPacketMapper;
    @Autowired
    private DelayQueueManager delayQueueManager;
    @Value("${wechat.spbill_create_ip}")
    private String spbill_create_ip;
    @Value("${wechat.notify_url}")
    private String notify_url;

    public AppOrderServiceImpl() {
    }

    public APP selectOrder(APPOrderDto selectOrderDto) {
        PageHelper.startPage(selectOrderDto.getPage(), selectOrderDto.getLimit());
        List<Map<String, Object>> orderList = this.orderMapper.selectOrders(selectOrderDto);
        String pay = this.orderMapper.selectOrdersByPay(selectOrderDto);
        String income = this.orderMapper.selectOrdersByIncome(selectOrderDto);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo(orderList);
        String msg = "支出 ￥" + pay + " 收入 ￥" + income;
        return APP.success(msg, pageInfo);
    }

    public APP payOrder(OrderDTO orderDTO) {
        Object result = this.checkPayOrder(orderDTO);
        if (result instanceof APP) {
            return (APP)result;
        } else {
            Map<String, Object> map = (Map)result;
            APP r = new APP();
            r.setCode(200);
            if (1 == orderDTO.getPayType()) {
                r = this.pay2Wallet((User)map.get("user"), (Wallet)map.get("wallet"), (Order)map.get("order"));
            } else {
                r.setCode(500);
                r.setMsg("暂不支持其他类型支付方式，请联系客服");
            }

            return r;
        }
    }

    public APP createOrder(CreateOrderDTO orderDTO) {
        Object result = this.checkCreateOrder(orderDTO);
        if (result instanceof APP) {
            return (APP)result;
        } else {
            User user = (User)result;
            APP r = new APP();
            r.setCode(200);
            orderDTO.setCreateTime(new Date());
            orderDTO.setUpdateTime(orderDTO.getCreateTime());
            orderDTO.setStartTime(orderDTO.getCreateTime());
            orderDTO.setOrderNo(LocalDateTime.now().format(MILLISECOND) + IdWorker.getIdStr());
            orderDTO.setUsername(user.getNickname());
            orderDTO.setUserPic(user.getAvatar());
            orderDTO.setStatus(0);
            orderDTO.setUserId(user.getUid());
            if (3 >= orderDTO.getOrderType()) {
                r = this.createRedPacket(user, orderDTO);
            } else if (4 == orderDTO.getOrderType()) {
                r = this.createRecharge(user, orderDTO);
            } else {
                if (5 != orderDTO.getOrderType()) {
                    r.setCode(500);
                    r.setMsg("暂不支持其他类型支付方式，请联系客服");
                    return r;
                }

                r = this.createWithdraw(user, orderDTO);
            }

            return r;
        }
    }

    public static void main(String[] args) {
        System.out.println(IdWorker.getMillisecond());
//        System.out.println(IdWorker.getTimeId()+M);
        String s = LocalDateTime.now().format(MILLISECOND) + IdWorker.getIdStr();
        System.out.println(s);
        System.out.println(s.length());
    }
    public APP getReceiveState(String userId, String orderId) {
        if (userId != null && orderId != null) {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("_uid", userId);
            User user = (User)this.userMapper.selectOne(queryWrapper);
            if (user == null) {
                return APP.fail("参数有误:userId:" + userId + ",该用户不存在", false);
            } else {
                Order order = (Order)this.orderMapper.selectById(orderId);
                if (order == null) {
                    return APP.fail("参数有误:orderId:" + orderId + ",该订单不存在", false);
                } else if (order.getStatus() != 1 && order.getStatus() != 2) {
                    return APP.fail("订单有误:orderId:" + orderId + ",status:" + order.getStatus() + ",该订单状态不可收取", false);
                } else {
                    if (1 != order.getOrderType() && 2 != order.getOrderType()) {
                        if (3 != order.getOrderType()) {
                            return APP.fail("订单有误:orderId:" + orderId + ",该订单收取有误", false);
                        }

                        if (!this.groupMapper.selectExitsUser(order.getTarget(), userId)) {
                            return APP.fail("订单有误:orderId:" + orderId + ",target:" + order.getTarget() + ",该订单收取人不匹配", false);
                        }
                        //判断是否已经领取了群红包
                        //
                        QueryWrapper<OrderRedPacket> redPacketQueryWrapper = new QueryWrapper<>();
                        redPacketQueryWrapper.eq("user_id",userId);
                        redPacketQueryWrapper.eq("order_id",order.getId());
                        OrderRedPacket orderRedPacket = this.redPacketMapper.selectOne(redPacketQueryWrapper);
                        if(orderRedPacket != null){
                            return APP.fail("红包已被领取", false);
                        }
                    } else if (!order.getTarget().equals(user.getUid())) {
                        return APP.fail("订单有误:orderId:" + orderId + ",target:" + order.getTarget() + ",该订单收取人不匹配", false);
                    }

                    return APP.success("可收取", true);
                }
            }
        } else {
            return APP.fail("参数错误，请对接好参数值", false);
        }
    }

    public APP getOrderDetails(String orderId) {
        if (orderId == null) {
            return APP.fail("参数错误，请对接好参数值", false);
        } else {
            Order order = this.orderMapper.selectById(orderId);
            if (order == null) {
                return APP.fail("参数有误:orderId:" + orderId + ",该订单不存在", false);
            } else {
                QueryWrapper<OrderItem> queryWrapper = new QueryWrapper();
                queryWrapper.eq("order_id", orderId);
                queryWrapper.orderByDesc("create_time");
                List<OrderItem> list = this.orderItemMapper.selectList(queryWrapper);
                if(list.size() > 0){
                    int index = 0;
                    double amount = 0;
                    for (int i = 0 ; i< list.size() ; i++){
                        if(Double.valueOf(list.get(i).getAmount()) > amount){
                            amount = Double.valueOf(list.get(i).getAmount());
                            index = i;
                        }
                    }
                    list.get(index).setIsStar(1);
                }
                order.setItems(list);
                return APP.success("订单详情获取成功", order);
            }
        }
    }

    public APP updateOrder(String userId, String orderId, String note) {
        APP receiveState = this.getReceiveState(userId, orderId);
        if ((Boolean)receiveState.getResult()) {
            Order order = (Order)this.orderMapper.selectById(orderId);
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("_uid", userId);
            User user = (User)this.userMapper.selectOne(queryWrapper);
            OrderItem item = new OrderItem();
            if (1 != order.getOrderType() && 2 != order.getOrderType()) {
                if (3 == order.getOrderType()) {
                    synchronized(order.getOrderNo().intern()) {
                        QueryWrapper<OrderRedPacket> redPacketQueryWrapper = new QueryWrapper<>();
                        // p.order_id = #{orderId} AND p.state = 0 order by p.`index` desc  limit 1
                        redPacketQueryWrapper.eq("order_id",orderId);
                        redPacketQueryWrapper.eq("state",0);
                        redPacketQueryWrapper.orderByDesc("`index`");
                        redPacketQueryWrapper.last(" limit 1");
                        OrderRedPacket redPacket = this.redPacketMapper.selectOne(redPacketQueryWrapper);
                        item.setAmount(redPacket.getAmount());
                        item.setCreateTime(order.getUpdateTime());
                        item.setNote(note);
                        item.setUpdateTime(item.getCreateTime());
                        item.setOrderId(Long.valueOf(orderId));
                        item.setOrderNo(order.getOrderNo());
                        item.setUserId(user.getUid());
                        item.setUserName(user.getNickname());
                        item.setUserPic(user.getAvatar());
                        this.orderItemMapper.insert(item);
                        redPacket.setState(1);
                        redPacket.setUserId(userId);
                        redPacket.setUpdateTime(new Date());
                        String amount = redPacket.getAmount();
                        this.redPacketMapper.updateById(redPacket);
                        Wallet wallet = this.walletMapper.selectByUserId(userId);
                        if (wallet == null) {
                            wallet = new Wallet();
                            wallet.setAmount("0.00");
                            wallet.setConsumptionAmount(wallet.getAmount());
                            wallet.setCreateTime(new Date());
                            wallet.setRechargeAmount(wallet.getRechargeAmount());
                            wallet.setUserId(userId);
                            this.walletMapper.insert(wallet);
                        }

                        this.walletMapper.updateAddAmount(wallet.getId(), order.getAmount(), new Date());
//                        QueryWrapper<OrderRedPacket> redPacketQueryWrapper = new QueryWrapper<>();
//                        // p.order_id = #{orderId} AND p.state = 0 order by p.`index` desc  limit 1
//                        redPacketQueryWrapper.eq("order_id",orderId);
//                        redPacketQueryWrapper.eq("state",0);
//                        redPacketQueryWrapper.orderByDesc("index");
//                        redPacketQueryWrapper.last(" limit 1");
                        redPacket = this.redPacketMapper.selectOne(redPacketQueryWrapper);

                        if (redPacket == null) {
                            order.setStatus(3);
                            order.setEndTime(order.getUpdateTime());
                        } else {
                            order.setStatus(2);
                        }

                        order.setUpdateTime(new Date());
                        this.orderMapper.updateById(order);
                        return APP.success("成功领取红包，金额：" + amount, order);
                    }
                } else {
                    return APP.fail("订单有误:orderId:" + note + ",该订单收取有误", false);
                }
            } else {
                order.setStatus(3);
                order.setUpdateTime(new Date());
                order.setEndTime(order.getUpdateTime());
                this.orderMapper.updateById(order);
                item.setAmount(order.getAmount());
                item.setCreateTime(order.getUpdateTime());
                item.setNote(note);
                item.setUpdateTime(item.getCreateTime());
                item.setOrderId(Long.valueOf(orderId));
                item.setOrderNo(order.getOrderNo());
                item.setUserId(user.getUid());
                item.setUserName(user.getNickname());
                item.setUserPic(user.getAvatar());
                this.orderItemMapper.insert(item);
                Wallet wallet = this.walletMapper.selectByUserId(userId);
                if (wallet == null) {
                    wallet = new Wallet();
                    wallet.setAmount("0.00");
                    wallet.setConsumptionAmount(wallet.getAmount());
                    wallet.setCreateTime(new Date());
                    wallet.setRechargeAmount(wallet.getConsumptionAmount());
                    wallet.setUserId(userId);
                    wallet.setUpdateTime(wallet.getCreateTime());
                    this.walletMapper.insert(wallet);
                }

                this.walletMapper.updateAddAmount(wallet.getId(), order.getAmount(), new Date());
                return APP.success("收取成功", order);
            }
        } else {
            return receiveState;
        }
    }

    public APP doWxOrder(HttpServletRequest request, String userId, String orderId) {
        Object result = this.checkDoWxOrder(userId, orderId);
        if (result instanceof APP) {
            return (APP)result;
        } else {
            Map<String, Object> map = (Map)result;
            WXPay wxPay = null;

            try {
                wxPay = new WXPay(WXPayConfigImpl.getInstance());
                Order order = (Order)map.get("order");
                UserWX userWX = (UserWX)map.get("userwx");
                Calendar instance = Calendar.getInstance();
                Date time_start = instance.getTime();
                instance.add(Calendar.MINUTE,5);
                Date time_expire = instance.getTime();
                Map<String, String> resultMap = wxPay.unifiedOrder(this.notify_url,
                        userWX.getOpenid(),
                        "APP", StringUtils.isEmpty(order.getNote()) ? "嗨聊用户充值" : order.getNote(),
                        order.getOrderNo(), order.getAmount(),
                        this.spbill_create_ip,
                        null, null, time_start, time_expire);

                String prepay_id = resultMap.get("prepay_id");
                if(StringUtils.isEmpty(prepay_id)){
                    return APP.fail("获取预支付id为空",resultMap);
                }
                String nonce_str = resultMap.get("nonce_str");
                Map<String, String> chooseWXPayMap = wxPay.chooseWXPayMap(prepay_id, nonce_str);
                System.out.println("map:" + chooseWXPayMap);
                return APP.success("获取下单参数成功", chooseWXPayMap);
            } catch (Exception var14) {
                var14.printStackTrace();
                return APP.fail("服务器错误", (Object)null);
            }
        }
    }

    public APP getPrepayId(HttpServletRequest request, String userId, String orderId) {
        Object result = this.checkDoWxOrder(userId, orderId);
        if (result instanceof APP) {
            return (APP)result;
        } else {
            Map<String, Object> map = (Map)result;
            WXPay wxPay = null;

            try {
                wxPay = new WXPay(WXPayConfigImpl.getInstance());
                Order order = (Order)map.get("order");
                UserWX userWX = (UserWX)map.get("userwx");
                Calendar instance = Calendar.getInstance();
                Date time_start = instance.getTime();
                instance.add(Calendar.MINUTE,5);
                Date time_expire = instance.getTime();
                Map<String, String> resultMap = wxPay.unifiedOrder(
                        this.notify_url, userWX.getOpenid(),
                        WXPayConstants.TRADE_TYPE_APP,
                        order.getNote() == null ? "嗨聊IM 余额充值" : order.getNote(),
                        order.getOrderNo(), order.getAmount(),
                        this.spbill_create_ip, null, null,
                        time_start, time_expire);
                String prepay_id = resultMap.get("prepay_id");
                return APP.success("获取下单预支付id参数成功", prepay_id);
            } catch (Exception var12) {
                var12.printStackTrace();
                return APP.fail("服务器错误", null);
            }
        }
    }

    private Object checkDoWxOrder(String userId, String orderId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("_uid", userId);
        User user = this.userMapper.selectOne(queryWrapper);
        if (user == null) {
            return APP.fail("参数有误:userId:" + userId + ",该用户不存在", (Object)null);
        } else {
            QueryWrapper<UserWX> wxQueryWrapper = new QueryWrapper();
            wxQueryWrapper.eq("user_id", userId);
            UserWX userWX = (UserWX)this.userWXMapper.selectOne(wxQueryWrapper);
            if (userWX != null && userWX.getOpenid() != null) {
                Order order = (Order)this.orderMapper.selectById(orderId);
                if (order == null) {
                    return APP.fail("参数有误:orderId:" + orderId + ",该订单不存在", (Object)null);
                } else if (order.getStatus() != 0) {
                    return APP.fail("参数有误:status:" + order.getStatus() + ",该订单状态不可充值", (Object)null);
                } else {
                    Map<String, Object> map = new HashMap();
                    map.put("user", user);
                    map.put("order", order);
                    map.put("userwx", userWX);
                    return map;
                }
            } else {
                return APP.fail("参数有误:userId:" + userId + ",该用户不存在授权微信信息", (Object)null);
            }
        }
    }

    private void randomHandOutAlgorithm(Long orderId, BigDecimal totalAmount, Integer size, Integer scale, BigDecimal minAmount) {
        BigDecimal remainAmount = totalAmount.setScale(scale, 1);
        Integer remainSize = size;
        OrderRedPacket redPacket = new OrderRedPacket();
        redPacket.setState(0);
        redPacket.setCreateTime(new Date());
        redPacket.setUpdateTime(new Date());
        redPacket.setOrderId(orderId);

        int index;
        for(index = 1; index < size; ++index) {
            BigDecimal random = BigDecimal.valueOf(Math.random());
            BigDecimal halfRemainSize = BigDecimal.valueOf((long)remainSize).divide(new BigDecimal(2), 0);
            BigDecimal max1 = remainAmount.divide(halfRemainSize, 1);
            BigDecimal minRemainAmount = minAmount.multiply(BigDecimal.valueOf((long)(remainSize - 1))).setScale(scale, 1);
            BigDecimal max2 = remainAmount.subtract(minRemainAmount);
            BigDecimal max = max1.compareTo(max2) < 0 ? max1 : max2;
            BigDecimal amount = random.multiply(max).setScale(scale, 1);
            if (amount.compareTo(minAmount) < 0) {
                amount = minAmount;
            }

            redPacket.setId((Long)null);
            redPacket.setAmount(amount.toString());
            redPacket.setIndex(index);
            this.redPacketMapper.insert(redPacket);
            remainAmount = remainAmount.subtract(amount).setScale(scale, 1);
            remainSize = remainSize - 1;
        }

        redPacket.setId((Long)null);
        redPacket.setAmount(remainAmount.toString());
        redPacket.setIndex(index);
        this.redPacketMapper.insert(redPacket);
    }

    private Object checkCreateOrder(CreateOrderDTO orderDTO) {
        if (orderDTO == null) {
            return APP.fail("参数错误，请对接好参数值", null);
        } else if (StringUtils.isEmpty(orderDTO.getUserId())) {
            return APP.fail("参数有误:userId:" + orderDTO.getUserId(), (Object)null);
        } else {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("_uid", orderDTO.getUserId());
            User user = this.userMapper.selectOne(queryWrapper);
            if (user == null) {
                return APP.fail("参数有误:userId:" + orderDTO.getUserId() + ",该用户不存在", (Object)null);
            } else {
                String amount = orderDTO.getAmount();
                if (Double.valueOf(amount) <= 0.0D) {
                    return APP.fail("参数有误:userId:" + orderDTO.getAmount() + ",金额小于等于0", (Object)null);
                } else {
                    Integer orderType = orderDTO.getOrderType();
                    if (orderType != null && 0 <= orderType && 5 >= orderType) {
                        if (3 >= orderDTO.getOrderType()) {
                            //校验密码
                            String password = orderDTO.getPassword();
                            if(StringUtils.isEmpty(password)){
                                return APP.fail("请输入支付密码",null);
                            }
                            UserPassword userPassword = new UserPassword();
                            userPassword.setUserId(orderDTO.getUserId());
                            userPassword.setPassword(password);
                            APP app = userPasswordService.checkPassword(userPassword);
                            if(app.getCode() != 200){
                                return APP.fail("支付密码校验失败，请重新输入或前往我的-支付设置密码",null);
                            }
                            if (StringUtils.isEmpty(orderDTO.getTarget())) {
                                return APP.fail("参数有误:target:" + orderDTO.getTarget(), (Object)null);
                            }

                            if (orderType == 3) {
                                QueryWrapper<Group> groupQueryWrapper = new QueryWrapper();
                                groupQueryWrapper.eq("_gid", orderDTO.getTarget());
                                Group group = (Group)this.groupMapper.selectOne(groupQueryWrapper);
                                if (group == null) {
                                    return APP.fail("参数有误:target:" + orderDTO.getTarget() + ",该群组不存在", (Object)null);
                                }

                                orderDTO.setTargetName(group.getName());
                            } else {
                                queryWrapper = new QueryWrapper();
                                queryWrapper.eq("_uid", orderDTO.getTarget());
                                User target = this.userMapper.selectOne(queryWrapper);
                                if (target == null) {
                                    return APP.fail("参数有误：target:" + orderDTO.getTarget() + ",该用户不存在", (Object)null);
                                }

                                orderDTO.setTargetName(target.getNickname());
                                orderDTO.setTargetPic(target.getAvatar());
                            }
                        }else if (4 == orderDTO.getOrderType()) {//充值
                            queryWrapper = new QueryWrapper();
                            queryWrapper.eq("_uid", orderDTO.getUserId());
                            User target = this.userMapper.selectOne(queryWrapper);
                            if (target == null) {
                                return APP.fail("参数有误：target:" + orderDTO.getTarget() + ",该用户不存在", (Object)null);
                            }
                            orderDTO.setTarget(orderDTO.getUserId());
                            orderDTO.setTargetName(target.getNickname());
                            orderDTO.setTargetPic(target.getAvatar());

                        } else if (5 == orderDTO.getOrderType()) {//提现

                            queryWrapper = new QueryWrapper();
                            queryWrapper.eq("_uid", orderDTO.getUserId());
                            User target = this.userMapper.selectOne(queryWrapper);
                            if (target == null) {
                                return APP.fail("参数有误：target:" + orderDTO.getTarget() + ",该用户不存在", (Object)null);
                            }
                            //校验密码
                            String password = orderDTO.getPassword();
                            if(StringUtils.isEmpty(password)){
                                return APP.fail("请输入支付密码",null);
                            }
                            UserPassword userPassword = new UserPassword();
                            userPassword.setUserId(orderDTO.getUserId());
                            userPassword.setPassword(password);
                            APP app = userPasswordService.checkPassword(userPassword);
                            if(app.getCode() != 200){
                                return APP.fail("支付密码校验失败，请重新输入或前往我的-支付设置密码",null);
                            }
                            orderDTO.setTarget(orderDTO.getUserId());
                            orderDTO.setTargetName(target.getNickname());
                            orderDTO.setTargetPic(target.getAvatar());
                            Wallet wallet = this.walletMapper.selectByUserId(user.getUid());
                            if (wallet == null || Double.valueOf(wallet.getAmount()) < Double.valueOf(orderDTO.getAmount())) {
                                return APP.fail("余额不足，请前往充值余额", null);
                            }
                        }

                        return user;
                    } else {
                        return APP.fail("参数有误:orderType:" + orderType, null);
                    }
                }
            }
        }
    }

    private APP createWithdraw(User user, CreateOrderDTO orderDTO) {
        Wallet wallet = this.walletMapper.selectByUserId(user.getUid());
        int count = this.walletMapper.updateAmount(wallet.getId(), orderDTO.getAmount(), new Date());
        if (count != 1) {
            return APP.fail("余额不足，请前往充值余额", (Object)null);
        } else {
            orderDTO.setBalance(2);
            int insert = this.orderMapper.insert(orderDTO);
            if (insert == 1) {
                Withdrawal wthdrawal = new Withdrawal();
                wthdrawal.setAmount(orderDTO.getAmount());
                wthdrawal.setCreateTime(new Date());
                wthdrawal.setUpateTime(wthdrawal.getCreateTime());
                wthdrawal.setOutRequestNo(orderDTO.getOrderNo());
                wthdrawal.setNote(orderDTO.getNote() == null ? "用户提现" : orderDTO.getNote());
                wthdrawal.setStatus(1);
                wthdrawal.setWithdrawalType(1);
                QueryWrapper<UserWX> queryWrapper = new QueryWrapper();
                queryWrapper.eq("user_id", user.getUid());
                UserWX userWX = this.userWXMapper.selectOne(queryWrapper);
                wthdrawal.setReceiverAccount(userWX.getOpenid());
                this.wthdrawalMapper.insert(wthdrawal);
                orderDTO.setWithdrawalId((long)wthdrawal.getId());
                this.orderMapper.updateById(orderDTO);
                boolean autoPay = dictMapper.selectAutoPay();
                if (autoPay) {
                    boolean b = this.wathdrawMoney2UserByWx(orderDTO, wthdrawal);
                    if(b) {
                        return APP.success("提现成功", orderDTO);
                    }
                    return APP.success("提现申请成功,但还未支持企业付款",orderDTO);
                } else {
                    return APP.success("提现申请成功", orderDTO);
                }
            } else {
                return APP.fail("提现订单创建失败", (Object)null);
            }
        }
    }

    private boolean wathdrawMoney2UserByWx(CreateOrderDTO orderDTO, Withdrawal wthdrawal) {
        WXPay wxPay = null;
        boolean flag = false;
        try {
            wxPay = new WXPay(WXPayConfigImpl.getInstance());
            Map<String, String> resultMap = wxPay.transfers(wthdrawal.getOutRequestNo(), wthdrawal.getReceiverAccount(), orderDTO.getAmount(), wthdrawal.getNote(), this.spbill_create_ip);
            wthdrawal.setResult(resultMap.toString());
            if ("SUCCESS".equalsIgnoreCase((String)resultMap.get("return_code")) && "SUCCESS".equalsIgnoreCase((String)resultMap.get("result_code"))) {
                wthdrawal.setTransactionId((String)resultMap.get("payment_no"));
                wthdrawal.setStatus(3);
                orderDTO.setStatus(3);
                orderDTO.setUpdateTime(new Date());
                this.orderMapper.updateById(orderDTO);
                flag = true;
            } else {
                wthdrawal.setStatus(4);
            }
            wthdrawal.setUpateTime(new Date());
            this.wthdrawalMapper.updateById(wthdrawal);
            System.out.println("wxPay.transfers:" + resultMap);
        } catch (Exception var5) {
            var5.printStackTrace();
        }
        return flag;
    }

    private APP createRecharge(User user, CreateOrderDTO orderDTO) {
        orderDTO.setBalance(1);
        int insert = this.orderMapper.insert(orderDTO);
        if (insert == 1) {
            this.pullNoPayCloseOrder(orderDTO);
            return APP.success("充值订单创建成功", orderDTO);
        } else {
            return APP.fail("充值订单创建失败", (Object)null);
        }
    }

    private APP<Object> createRedPacket(User user, CreateOrderDTO orderDTO) {
        orderDTO.setBalance(2);
        if (orderDTO.getCount() == null) {
            orderDTO.setCount(1);
        }

        int insert = this.orderMapper.insert(orderDTO);
        if (orderDTO.getOrderType() == 3) {
            this.randomHandOutAlgorithm((long)orderDTO.getId(), new BigDecimal(orderDTO.getAmount()), orderDTO.getCount(), 2, new BigDecimal("0.01"));
        }

        if (insert == 1) {
            this.pullNoPayCloseOrder(orderDTO);
            return APP.success("红包创建成功", orderDTO);
        } else {
            return APP.fail("红包创建失败", (Object)null);
        }
    }

    private void pullNoPayCloseOrder(CreateOrderDTO orderDTO) {
        orderDTO.setIdentifier("noPayOrder" + orderDTO.getId());
        DelayTask delayTask = new DelayTask(orderDTO, 5L, TimeUnit.MINUTES);
        this.delayQueueManager.put(delayTask);
    }

    private Object checkPayOrder(OrderDTO orderDTO) {
        if (orderDTO == null) {
            return APP.fail("参数错误，请对接好参数值",null);
        }

        if (StringUtils.isEmpty(orderDTO.getUserId())) {
            return APP.fail("参数有误:userId:" + orderDTO.getUserId(),null);
        } else {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.eq("_uid", orderDTO.getUserId());
            User user = (User)this.userMapper.selectOne(queryWrapper);
            if (user == null) {
                return APP.fail("参数有误:userId:" + orderDTO.getUserId() + ",该用户存在",null);
            }
            if (StringUtils.isEmpty(orderDTO.getOrderId())) {
                return APP.fail("参数有误:orderId:" + orderDTO.getOrderId(),null);
            } else {
                Order order = (Order)this.orderMapper.selectById(orderDTO.getOrderId());
                if (order == null) {
                    return APP.fail("参数有误:orderId:" + orderDTO.getOrderId() + ",该订单不存在",null);
                } else if (order.getStatus() != 0) {
                    return APP.fail("订单有误:orderId:" + orderDTO.getOrderId() + ",该订单状态为" + order.getStatus() + "不可支付",null);
                } else {
                    Wallet wallet = this.walletMapper.selectByUserId(user.getUid());
                    if (wallet == null) {
                        return APP.fail("用户余额不足，请前往支付",null);
                    } else {
                        Map<String, Object> map = new HashMap();
                        map.put("user", user);
                        map.put("order", order);
                        map.put("wallet", wallet);
                        return map;
                    }
                }
            }
        }
    }

    private APP<Order> pay2Wallet(User user, Wallet wallet, Order order) {
        int count = this.walletMapper.updateAmount(wallet.getId(), order.getAmount(), new Date());
        if (count == 1) {
            order.setPayType(1);
            order.setStatus(1);
            order.setUpdateTime(new Date());
            this.orderMapper.updateById(order);
            this.pullPayCloseOrder(order);
            return APP.success("支付成功",order);
        } else {
            return APP.fail("余额不足，请前往充值余额",null);
        }
    }

    private void pullPayCloseOrder(Order order) {
        order.setIdentifier("payOrder" + order.getId());
        DelayTask delayTask = new DelayTask(order, 1L, TimeUnit.DAYS);
        this.delayQueueManager.put(delayTask);
        order.setIdentifier("noPayOrder" + order.getId());
        delayTask = new DelayTask(order, 1L, TimeUnit.DAYS);
        this.delayQueueManager.remove(delayTask);
    }
}
